package com.swap.common.core.controller;


import com.swap.common.constant.Constants;
import com.swap.common.core.domain.AjaxResult;
import com.swap.common.core.domain.model.DevOrProd;
import com.swap.common.core.domain.model.LoginUser;
import com.swap.common.core.redis.RedisCache;
import com.swap.common.exception.AuthenticationException;
import com.swap.common.exception.BusinessException;
import com.swap.common.utils.DateUtils;
import com.swap.common.utils.StringUtils;
import com.swap.common.utils.XGSEncryptUtil;
import com.swap.common.utils.sign.Md5Utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;

import java.beans.PropertyEditorSupport;
import java.util.Date;

/**
 * web层通用数据处理
 *
 * @author xgs
 */
public class BaseController {
    protected final Logger log = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private RedisCache redisCache;
    @Autowired
    private DevOrProd devOrProd;

    /**
     * 将前台传递过来的日期格式的字符串，自动转化为Date类型
     */
    @InitBinder
    public void initBinder(WebDataBinder binder) {
        // Date 类型转换
        binder.registerCustomEditor(Date.class, new PropertyEditorSupport() {
            @Override
            public void setAsText(String text) {
                setValue(DateUtils.parseDate(text));
            }
        });
    }

    /**
     * 验证token
     *
     * @param methodName 方法名
     * @param user       用户工号
     * @param token      token
     */
    private void tokenVerify(String methodName, String user, String token) {
        if (StringUtils.isEmpty(token)) {
            log.info(methodName + ":鉴权失败,缺少token");
            throw new BusinessException("鉴权失败,缺少token");
        }

        LoginUser loginUser = redisCache.getCacheObject(user);
        if (StringUtils.isNull(loginUser)) {
            log.info(methodName + ":鉴权失败,未找到该用户登录信息");
            throw new BusinessException("鉴权失败,未找到该用户登录信息");
        }

        if (!loginUser.getToken().equals(token)) {
            log.info(methodName + ":鉴权失败,token与用户不匹配");
            throw new BusinessException("鉴权失败,token与用户不匹配");
        }
    }

    /**
     * 接口鉴权（有参）
     *
     * @param headers     请求头
     * @param requestData 请求体
     * @param tokenVerify true-验证token
     */
    public void authentication(String methodName, HttpHeaders headers, String requestData, boolean tokenVerify) {
        try {
            if (!devOrProd.getProdFlag()) {
                return;
            }
            //提取信息头中的信息
            String user = headers.getFirst("user");
            String pass = headers.getFirst("pass");
            String md5 = headers.getFirst("md5");

            //验证header
            if (StringUtils.isEmpty(user) || StringUtils.isEmpty(pass) || StringUtils.isEmpty(md5)) {
                log.info(methodName + ":鉴权失败,鉴权信息不完整");
                throw new AuthenticationException("鉴权失败,鉴权信息不完整");
            }

            //验证token
            if (tokenVerify) {
                String token = headers.getFirst("token");
                tokenVerify(methodName, user, token);
            }

            //解密
            String strHeaderPass = XGSEncryptUtil.EncryptEx(pass, false, Constants.ENCRYPT_KEY, false);
            //md5加密
            String strMd5 = Md5Utils.hash(requestData);

            if (!strHeaderPass.equals(Constants.HTTPHEADER_PASS)) {
                log.info(methodName + ":鉴权失败");
                throw new AuthenticationException("鉴权失败");
            }

            if (!md5.equalsIgnoreCase(strMd5)) {
                log.info(methodName + ":md5验证失败");
                throw new AuthenticationException("md5验证失败");
            }
        } catch (Exception e) {
            throw new AuthenticationException(e.getMessage());
        }
    }


    /**
     * 接口鉴权(无参)
     *
     * @param headers 请求头
     */
    public void authentication(String methodName, HttpHeaders headers) {
        try {
            if (!devOrProd.getProdFlag()) {
                return;
            }
            //提取信息头中的信息
            String user = headers.getFirst("user");
            String pass = headers.getFirst("pass");
            String token = headers.getFirst("token");

            //验证header
            if (StringUtils.isEmpty(user) || StringUtils.isEmpty(pass)) {
                log.info(methodName + ":鉴权失败,鉴权信息不完整");
                throw new AuthenticationException("鉴权失败,鉴权信息不完整");
            }

            //验证token
            tokenVerify(methodName, user, token);

            //解密
            String strHeaderPass = XGSEncryptUtil.EncryptEx(pass, false, Constants.ENCRYPT_KEY, false);

            if (!strHeaderPass.equals(Constants.HTTPHEADER_PASS)) {
                log.info(methodName + ":鉴权失败");
                throw new AuthenticationException("鉴权失败");
            }
        } catch (Exception e) {
            throw new AuthenticationException(e.getMessage());
        }
    }

    /**
     * 返回成功
     */
    public AjaxResult success() {
        return AjaxResult.success();
    }

    /**
     * 返回失败消息
     */
    public AjaxResult error() {
        return AjaxResult.error();
    }

    /**
     * 返回成功消息
     */
    public AjaxResult success(String message) {
        return AjaxResult.success(message);
    }

    /**
     * 返回成功消息
     */
    public AjaxResult success(Object data) {
        return AjaxResult.success(data);
    }

    /**
     * 返回失败消息
     */
    public AjaxResult error(String message) {
        return AjaxResult.error(message);
    }

    /**
     * 返回失败消息
     */
    public AjaxResult error(int code, String message) {
        return AjaxResult.error(code, message);
    }

    /**
     * 响应返回结果
     *
     * @param rows 影响行数
     * @return 操作结果
     */
    protected AjaxResult toAjax(int rows) {
        return rows > 0 ? AjaxResult.success() : AjaxResult.error();
    }

    /**
     * 响应返回结果
     *
     * @param result 结果
     * @return 操作结果
     */
    protected AjaxResult toAjax(boolean result) {
        return result ? success() : error();
    }

    /**
     * 页面跳转
     */
    public String redirect(String url) {
        return StringUtils.format("redirect:{}", url);
    }

}
